<template>
  <div class="service-calendar">
    <div class="calendar-header">
      <h3 class="calendar-title">服务日历</h3>
      <span class="all-calendar" @click="goToBookingHistory">查看全部 ></span>
    </div>
    
    <div class="calendar-months-container">
      <div class="calendar-months" ref="monthsContainer">
        <div
          v-for="month in months"
          :key="month.value"
          class="month-item"
          :class="{ active: month.value === selectedMonth }"
          @click="selectMonth(month.value)"
        >
          {{ month.label }}
          <span v-if="getMonthBookingCount(month.value) > 0" class="booking-count">
            {{ getMonthBookingCount(month.value) }}
          </span>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载预约数据中...</span>
    </div>
    
    <!-- 预约记录和活动列表 -->
    <div v-else-if="filteredBookings.length > 0 || hasActivityForMonth" class="bookings-list">
      <!-- 预约记录 -->
      <div
        v-for="booking in filteredBookings"
        :key="booking.id"
        class="booking-item"
        @click="handleBookingClick(booking)"
      >
        <div class="booking-date">
          <div class="date-day">{{ getDayFromDate(booking.appointmentDate) }}</div>
          <div class="date-month">{{ getMonthFromDate(booking.appointmentDate) }}</div>
        </div>
        <div class="booking-info">
          <div class="booking-service">{{ booking.serviceName }}</div>
          <div class="booking-time">{{ booking.appointmentTime }}</div>
          <div class="booking-address">{{ booking.address }}</div>
        </div>
        <div class="booking-status" :class="getStatusClass(booking.status)">
          {{ booking.status }}
        </div>
      </div>
      
      <!-- 活动卡片（合并到预约记录中） -->
      <div class="activity-card" v-if="hasActivityForMonth">
        <div class="activity-info">
          <div class="activity-date">{{ serviceActivity.name }}</div>
          <div class="activity-content">
            <h4 class="activity-title">{{ serviceActivity.title }}</h4>
            <p class="activity-subtitle">{{ serviceActivity.subTitle }}</p>
            <button class="join-btn" @click="joinActivity">立即参与</button>
          </div>
        </div>
        <div class="activity-image">
          <img :src="serviceActivity.img" :alt="serviceActivity.title" />
        </div>
      </div>
    </div>
    
    
    <!-- 无预约记录也无活动 -->
    <div v-else class="empty-state">
      <img src="@/assets/imgs/search_null_data.png" alt="暂无预约" class="empty-image" />
      <p class="empty-text">本月暂无预约记录</p>
      <p class="empty-subtitle">快去预约服务吧！</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { getServiceBookingHistoryApi } from '@/api/service'

const router = useRouter()

const props = defineProps({
  serviceActivity: {
    type: Object,
    default: () => ({})
  }
})

// 响应式数据
const loading = ref(false)
const bookings = ref([])
const selectedMonth = ref(new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : (new Date().getMonth() + 1).toString())
const monthsContainer = ref(null)

// 生成完整的12个月份配置
const months = Array.from({ length: 12 }, (_, index) => {
  const month = index + 1
  const monthValue = month < 10 ? '0' + month : month.toString()
  const monthLabel = month + '月'
  return { value: monthValue, label: monthLabel }
})

// 计算属性：根据选中月份过滤预约记录
const filteredBookings = computed(() => {
  if (!bookings.value.length) return []
  
  return bookings.value.filter(booking => {
    const appointmentDate = new Date(booking.appointmentDate)
    const month = (appointmentDate.getMonth() + 1).toString().padStart(2, '0')
    return month === selectedMonth.value
  }).sort((a, b) => new Date(a.appointmentDate) - new Date(b.appointmentDate))
})

// 计算属性：当前月份是否有活动
const hasActivityForMonth = computed(() => {
  if (!props.serviceActivity.name) return false
  
  // 根据活动名称判断月份，这里可以根据实际需求调整
  const activityMonth = props.serviceActivity.name.includes('12.9-12.19') ? '12' : null
  return activityMonth === selectedMonth.value
})

// 获取预约记录
const getBookings = async () => {
  try {
    loading.value = true
    const response = await getServiceBookingHistoryApi()
    
    console.log('服务日历获取预约记录响应:', response)
    
    if (response && (response.code === 0 || response.code === 200)) {
      bookings.value = response.data || []
      console.log('预约记录数据:', bookings.value)
    } else {
      console.error('获取预约记录失败:', response)
    }
  } catch (error) {
    console.error('获取预约记录失败:', error)
    ElMessage.error('获取预约记录失败')
  } finally {
    loading.value = false
  }
}

// 选择月份
const selectMonth = (month) => {
  selectedMonth.value = month
  console.log(`选择了${month}月，当前预约记录:`, filteredBookings.value)
  
  // 滚动到选中的月份
  scrollToSelectedMonth(month)
}

// 滚动到选中的月份
const scrollToSelectedMonth = (month) => {
  if (!monthsContainer.value) return
  
  const monthIndex = months.findIndex(m => m.value === month)
  if (monthIndex === -1) return
  
  const monthElement = monthsContainer.value.children[monthIndex]
  if (monthElement) {
    monthElement.scrollIntoView({
      behavior: 'smooth',
      block: 'nearest',
      inline: 'center'
    })
  }
}

// 获取月份预约数量
const getMonthBookingCount = (month) => {
  if (!bookings.value.length) return 0
  
  return bookings.value.filter(booking => {
    const appointmentDate = new Date(booking.appointmentDate)
    const bookingMonth = (appointmentDate.getMonth() + 1).toString().padStart(2, '0')
    return bookingMonth === month
  }).length
}

// 从日期获取天数
const getDayFromDate = (dateString) => {
  const date = new Date(dateString)
  return date.getDate()
}

// 从日期获取月份
const getMonthFromDate = (dateString) => {
  const date = new Date(dateString)
  return (date.getMonth() + 1) + '月'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    '待确认': 'status-pending',
    '已确认': 'status-confirmed',
    '已完成': 'status-completed',
    '已取消': 'status-cancelled'
  }
  return statusMap[status] || 'status-default'
}

// 处理预约点击
const handleBookingClick = (booking) => {
  console.log('点击预约记录:', booking)
  // 可以跳转到预约详情页面或显示详情弹窗
  ElMessage.info(`查看预约详情：${booking.serviceName}`)
}

// 跳转到预约历史页面
const goToBookingHistory = () => {
  router.push('/service-booking-history')
}

// 参与活动
const joinActivity = () => {
  ElMessage.success('立即参与活动！')
}

onMounted(() => {
  getBookings()
  
  // 初始化时滚动到当前月份
  nextTick(() => {
    scrollToSelectedMonth(selectedMonth.value)
  })
})
</script>

<style scoped>
.service-calendar {
  background-color: #fff;
  margin: 0 16px 20px;
  border-radius: 16px;
  padding: 20px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.calendar-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.all-calendar {
  font-size: 14px;
  color: #409eff;
  cursor: pointer;
}

.all-calendar:hover {
  text-decoration: underline;
}

.calendar-months-container {
  margin-bottom: 20px;
  position: relative;
}

.calendar-months {
  display: flex;
  gap: 12px;
  overflow-x: auto;
  padding: 8px 0 12px 0;
  scroll-behavior: smooth;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.calendar-months::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

.month-item {
  flex-shrink: 0;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #666;
  background-color: #f5f5f5;
  border: 1px solid transparent;
  white-space: nowrap;
  position: relative;
}

.month-item:hover {
  background-color: #e6f4ff;
  color: #409eff;
}

.month-item.active {
  background-color: #409eff;
  color: white;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.booking-count {
  background-color: #ff4757;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  margin-left: 4px;
  min-width: 16px;
  text-align: center;
  line-height: 1;
}

.month-item.active .booking-count {
  background-color: rgba(255, 255, 255, 0.3);
}


/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #666;
}

/* 预约记录列表样式 */
.bookings-list {
  margin-bottom: 20px;
}

/* 活动卡片样式（合并到预约记录中） */
.activity-card {
  background: linear-gradient(135deg, #4CAF50 0%, #8BC34A 100%);
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  color: white;
  position: relative;
  overflow: hidden;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.activity-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.3);
}

.activity-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('@/assets/imgs/service_bg.png') no-repeat right center;
  background-size: contain;
  opacity: 0.1;
  pointer-events: none;
}

.activity-info {
  flex: 1;
  position: relative;
  z-index: 2;
}

.activity-date {
  font-size: 12px;
  margin-bottom: 8px;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.activity-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.activity-subtitle {
  font-size: 12px;
  margin: 0 0 16px 0;
  line-height: 1.4;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.join-btn {
  background-color: #fff;
  color: #4CAF50;
  border: none;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.join-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.activity-image {
  width: 60px;
  height: 60px;
  margin-left: 16px;
  position: relative;
  z-index: 2;
}

.activity-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.booking-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  background-color: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 4px solid #409eff;
}

.booking-item:hover {
  background-color: #e6f4ff;
  transform: translateX(4px);
}

.booking-date {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 12px;
  min-width: 50px;
}

.date-day {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
  line-height: 1;
}

.date-month {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.booking-info {
  flex: 1;
  min-width: 0;
}

.booking-service {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.booking-time {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.booking-address {
  font-size: 11px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.booking-status {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  white-space: nowrap;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-confirmed {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-completed {
  background-color: #d4edda;
  color: #155724;
}

.status-cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  margin-bottom: 20px;
}

.empty-image {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  color: #999;
  font-size: 14px;
  margin: 0 0 4px 0;
}

.empty-subtitle {
  color: #ccc;
  font-size: 12px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .service-calendar {
    margin: 0 12px 16px;
    padding: 16px 12px;
  }
  
  .calendar-title {
    font-size: 16px;
  }
  
  .all-calendar {
    font-size: 12px;
  }
  
  .calendar-months {
    gap: 8px;
    padding: 6px 0 10px 0;
  }
  
  .month-item {
    padding: 6px 12px;
    font-size: 12px;
  }
  
  .activity-card {
    padding: 12px;
  }
  
  .activity-title {
    font-size: 14px;
  }
  
  .activity-subtitle {
    font-size: 11px;
  }
  
  .join-btn {
    padding: 6px 12px;
    font-size: 11px;
  }
  
  .activity-image {
    width: 50px;
    height: 50px;
    margin-left: 12px;
  }
  
  .booking-item {
    padding: 10px;
  }
  
  .booking-date {
    min-width: 40px;
    margin-right: 8px;
  }
  
  .date-day {
    font-size: 16px;
  }
  
  .booking-service {
    font-size: 13px;
  }
  
  .booking-time {
    font-size: 11px;
  }
  
  .booking-address {
    font-size: 10px;
  }
  
  .booking-status {
    font-size: 10px;
    padding: 3px 6px;
  }
  
  .activity-card {
    padding: 12px;
  }
  
  .activity-title {
    font-size: 14px;
  }
  
  .activity-subtitle {
    font-size: 11px;
  }
  
  .join-btn {
    padding: 6px 12px;
    font-size: 11px;
  }
  
  .activity-image {
    width: 50px;
    height: 50px;
    margin-left: 12px;
  }
}
</style>
